package sv.com.seguros.dso.asg;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import sv.com.seguros.dso.BaseServiceImpl;
import sv.com.seguros.dto.asg.AsgPago;
import sv.com.seguros.exception.WebException;
import sv.com.seguros.web.util.WebUtilidades;

public class AsgPagoServiceImpl extends BaseServiceImpl implements AsgPagoService {
	
	@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = {Exception.class, WebException.class})
	public void generatePay(AsgPago asgPago, List<Long> asgAbonosId) throws WebException{
		if(WebUtilidades.isEmptyList(asgAbonosId))
			throw new WebException("Debe seleccionar al menos una cuota a pagar");
		try{
			asgPago.setSgdUsuario(WebUtilidades.getSgdUsuarioFromAcegi());
			asgPago.setAsgPagoFecha(WebUtilidades.dateFormatAsYYYYMMDDHHMMSS.format(new Date()));
			save(asgPago);
			String hqlQuery = "update AsgAbono set asgPago.asgPagoId = :asgPagoId where asgAbonoId in (:asgAbonosId)";
			Map<String, Object> parameters = new HashMap<String, Object>();
			parameters.put("asgPagoId", asgPago.getAsgPagoId());
			parameters.put("asgAbonosId", asgAbonosId);
			executeNonHibernateQuery(hqlQuery, parameters);
		}catch(Exception e){
			logger.error("Exception:", e);
			throw new WebException("Problemas al tratar de guardar la informaci\u00F3n");
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = {Exception.class, WebException.class})
	public void deleteAsgPago(Long asgPagoId) throws Exception{
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("asgPagoId", asgPagoId);
		String hqlQuery = "update AsgAbono set asgPago.asgPagoId = null where asgPago.asgPagoId = :asgPagoId)";
		executeNonHibernateQuery(hqlQuery, parameters);
		hqlQuery = "delete from AsgPago where asgPagoId = :asgPagoId";
		executeNonHibernateQuery(hqlQuery, parameters);
	}

}
